serialize.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import base64
  2. import io
  3. import json
  4. import zlib
  5. from pip._vendor import msgpack
  6. from pip._vendor.requests.structures import CaseInsensitiveDict
  7. from .compat import HTTPResponse, pickle, text_type
  8. def _b64_decode_bytes(b):
  9. return base64.b64decode(b.encode("ascii"))
  10. def _b64_decode_str(s):
  11. return _b64_decode_bytes(s).decode("utf8")
  12. class Serializer(object):
  13. def dumps(self, request, response, body=None):
  14. response_headers = CaseInsensitiveDict(response.headers)
  15. if body is None:
  16. body = response.read(decode_content=False)
  17. # NOTE: 99% sure this is dead code. I'm only leaving it
  18. # here b/c I don't have a test yet to prove
  19. # it. Basically, before using
  20. # `cachecontrol.filewrapper.CallbackFileWrapper`,
  21. # this made an effort to reset the file handle. The
  22. # `CallbackFileWrapper` short circuits this code by
  23. # setting the body as the content is consumed, the
  24. # result being a `body` argument is *always* passed
  25. # into cache_response, and in turn,
  26. # `Serializer.dump`.
  27. response._fp = io.BytesIO(body)
  28. # NOTE: This is all a bit weird, but it's really important that on
  29. # Python 2.x these objects are unicode and not str, even when
  30. # they contain only ascii. The problem here is that msgpack
  31. # understands the difference between unicode and bytes and we
  32. # have it set to differentiate between them, however Python 2
  33. # doesn't know the difference. Forcing these to unicode will be
  34. # enough to have msgpack know the difference.
  35. data = {
  36. u"response": {
  37. u"body": body,
  38. u"headers": dict(
  39. (text_type(k), text_type(v)) for k, v in response.headers.items()
  40. ),
  41. u"status": response.status,
  42. u"version": response.version,
  43. u"reason": text_type(response.reason),
  44. u"strict": response.strict,
  45. u"decode_content": response.decode_content,
  46. }
  47. }
  48. # Construct our vary headers
  49. data[u"vary"] = {}
  50. if u"vary" in response_headers:
  51. varied_headers = response_headers[u"vary"].split(",")
  52. for header in varied_headers:
  53. header = text_type(header).strip()
  54. header_value = request.headers.get(header, None)
  55. if header_value is not None:
  56. header_value = text_type(header_value)
  57. data[u"vary"][header] = header_value
  58. return b",".join([b"cc=4", msgpack.dumps(data, use_bin_type=True)])
  59. def loads(self, request, data):
  60. # Short circuit if we've been given an empty set of data
  61. if not data:
  62. return
  63. # Determine what version of the serializer the data was serialized
  64. # with
  65. try:
  66. ver, data = data.split(b",", 1)
  67. except ValueError:
  68. ver = b"cc=0"
  69. # Make sure that our "ver" is actually a version and isn't a false
  70. # positive from a , being in the data stream.
  71. if ver[:3] != b"cc=":
  72. data = ver + data
  73. ver = b"cc=0"
  74. # Get the version number out of the cc=N
  75. ver = ver.split(b"=", 1)[-1].decode("ascii")
  76. # Dispatch to the actual load method for the given version
  77. try:
  78. return getattr(self, "_loads_v{}".format(ver))(request, data)
  79. except AttributeError:
  80. # This is a version we don't have a loads function for, so we'll
  81. # just treat it as a miss and return None
  82. return
  83. def prepare_response(self, request, cached):
  84. """Verify our vary headers match and construct a real urllib3
  85. HTTPResponse object.
  86. """
  87. # Special case the '*' Vary value as it means we cannot actually
  88. # determine if the cached response is suitable for this request.
  89. # This case is also handled in the controller code when creating
  90. # a cache entry, but is left here for backwards compatibility.
  91. if "*" in cached.get("vary", {}):
  92. return
  93. # Ensure that the Vary headers for the cached response match our
  94. # request
  95. for header, value in cached.get("vary", {}).items():
  96. if request.headers.get(header, None) != value:
  97. return
  98. body_raw = cached["response"].pop("body")
  99. headers = CaseInsensitiveDict(data=cached["response"]["headers"])
  100. if headers.get("transfer-encoding", "") == "chunked":
  101. headers.pop("transfer-encoding")
  102. cached["response"]["headers"] = headers
  103. try:
  104. body = io.BytesIO(body_raw)
  105. except TypeError:
  106. # This can happen if cachecontrol serialized to v1 format (pickle)
  107. # using Python 2. A Python 2 str(byte string) will be unpickled as
  108. # a Python 3 str (unicode string), which will cause the above to
  109. # fail with:
  110. #
  111. # TypeError: 'str' does not support the buffer interface
  112. body = io.BytesIO(body_raw.encode("utf8"))
  113. return HTTPResponse(body=body, preload_content=False, **cached["response"])
  114. def _loads_v0(self, request, data):
  115. # The original legacy cache data. This doesn't contain enough
  116. # information to construct everything we need, so we'll treat this as
  117. # a miss.
  118. return
  119. def _loads_v1(self, request, data):
  120. try:
  121. cached = pickle.loads(data)
  122. except ValueError:
  123. return
  124. return self.prepare_response(request, cached)
  125. def _loads_v2(self, request, data):
  126. try:
  127. cached = json.loads(zlib.decompress(data).decode("utf8"))
  128. except (ValueError, zlib.error):
  129. return
  130. # We need to decode the items that we've base64 encoded
  131. cached["response"]["body"] = _b64_decode_bytes(cached["response"]["body"])
  132. cached["response"]["headers"] = dict(
  133. (_b64_decode_str(k), _b64_decode_str(v))
  134. for k, v in cached["response"]["headers"].items()
  135. )
  136. cached["response"]["reason"] = _b64_decode_str(cached["response"]["reason"])
  137. cached["vary"] = dict(
  138. (_b64_decode_str(k), _b64_decode_str(v) if v is not None else v)
  139. for k, v in cached["vary"].items()
  140. )
  141. return self.prepare_response(request, cached)
  142. def _loads_v3(self, request, data):
  143. # Due to Python 2 encoding issues, it's impossible to know for sure
  144. # exactly how to load v3 entries, thus we'll treat these as a miss so
  145. # that they get rewritten out as v4 entries.
  146. return
  147. def _loads_v4(self, request, data):
  148. try:
  149. cached = msgpack.loads(data, raw=False)
  150. except ValueError:
  151. return
  152. return self.prepare_response(request, cached)